package pr.lanmu.config.util;


import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import pr.lanmu.config.base.UserBase;

import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

/**
 * 当前登录人信息类
 */
public class Current {

    public static final ThreadLocal<Info> threadLocal = new ThreadLocal<>();
    private static final String NO_LOGIN_NAME = "访客";

    public static void setRequest(HttpServletRequest request) {
        threadLocal
                .set(Info.builder()
                        .request(request)
                        .requestRandomId(UUID.randomUUID()
                                .toString())
                        .build());
    }

    public static Info getInfo() {
        return Optional.ofNullable(threadLocal.get())
                .orElse(new Info());
    }

    public static UserBase getUser() {
        return getInfo().getUserBase();
    }

    public static void setUser(UserBase userBase) {
        threadLocal.get().setUserBase(userBase);
    }

    public static Long getUserId() {
        return Optional.ofNullable(getUser())
                .orElse(new UserBase())
                .getId();
    }

    public static String getRequestFlag() {
        Info info = Current.getInfo();
        UserBase userBase = info.getUserBase();
        String loginAccount = NO_LOGIN_NAME;
        if (Objects.nonNull(userBase)) loginAccount = "用户id:" + userBase.getId()
                .toString();
        String requestRandomId = info.getRequestRandomId();
        if (Objects.isNull(requestRandomId)) return StrUtil.EMPTY;
        return loginAccount + "(请求ID:" + requestRandomId + ")";
    }

    /**
     * 清除
     */
    public static void clear() {
        threadLocal.remove();
    }

    @Data
    @Builder
    @Accessors(chain = true)
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Info {
        private UserBase userBase;
        private HttpServletRequest request;
        private String requestRandomId;
    }
}